package com.alibaba.citrus.cr.sales.plan.repository;

import com.alibaba.citrus.cr.common.annotation.RepositoryInvoker;
import com.alibaba.citrus.cr.common.exception.RepositoryException;
import com.alibaba.citrus.cr.common.util.DateUtils;
import com.alibaba.citrus.cr.sales.plan.dto.api.request.BatchQuerySalesPlanRequest;
import com.alibaba.citrus.cr.sales.plan.dto.api.request.PageQuerySalePlanRequest;
import com.alibaba.citrus.cr.sales.plan.dto.api.request.QuerySalesPlanRequest;
import com.alibaba.citrus.cr.sales.plan.model.enums.SalesPlanStatusEnum;
import com.alibaba.citrus.cr.sales.plan.model.features.SalesPlanFeatures;
import com.alibaba.citrus.cr.sales.plan.sdo.SalesPlanSDO;
import com.alibaba.cz.base.tool.StringUtil;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.cz.base.tool.page.PageResult;
import com.alibaba.fastjson.JSON;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.bcorder.sales_plan.salesplan.dto.BatchQuerySalesPlanResponse;
import com.epoch.app.bcorder.sales_plan.salesplan.dto.CreateSalesPlanResponse;
import com.epoch.app.bcorder.sales_plan.salesplan.dto.LoadLatelySalesPlanRequest;
import com.epoch.app.bcorder.sales_plan.salesplan.dto.LoadLatelySalesPlansRequest;
import com.epoch.app.bcorder.sales_plan.salesplan.dto.LoadSalesPlanListRequest;
import com.epoch.app.bcorder.sales_plan.salesplan.dto.LoadSalesPlanRequest;
import com.epoch.app.bcorder.sales_plan.salesplan.dto.UpdateSalesPlanStatusRequest;
import com.epoch.app.bcorder.sales_plan.salesplan.dto.UpdateSalesPlanStatusResponse;
import com.epoch.app.bcorder.sales_plan.salesplan.model.SalesPlan;
import com.epoch.app.bcorder.sales_plan.salesplan.service.SalesPlanService;
import com.epoch.app.crplatformenhance.api.organizationquery.service.OrganizationQueryService;
import com.epoch.app.crplatformenhance.model.dto.QuerySuperiorSalesOrganizationResponse;
import com.google.common.collect.Lists;
import net.sf.json.JSONObject;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author yuhailin
 * @description:
 * @date 2021-09-06 15:53
 */
@Component
public class SalesPlanRepositoryImpl implements SalesPlanRepository {
    private static Log log = Log.getLogger(SalesPlanRepositoryImpl.class);

    @Resource
    SalesPlanService salesPlanService;

    @Resource
    OrganizationQueryService organizationQueryService;

    @Override
    @RepositoryInvoker(printLog = true)
    public String save(SalesPlanSDO salesPlanSDO) {
        SalesPlan salesPlan = salesPlanConverter(salesPlanSDO);
        try {
            CreateSalesPlanResponse createSalesPlanResponse = salesPlanService.createSalesPlan(salesPlan);
            return createSalesPlanResponse.getLastInsertId();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    @RepositoryInvoker(printLog = true)
    public Boolean edit(SalesPlanSDO salesPlanSDO) {
        SalesPlan salesPlan = salesPlanConverter(salesPlanSDO);
        try {
            Integer count = salesPlanService.updateSalesPlan(salesPlan).getCount();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RepositoryException("数据更新失败");
        }
        return true;
    }

    /**
     * 编辑月度计划
     *
     * @param salesPlanSDO
     * @return
     */
    @Override
    public Boolean editSalesPlan(SalesPlanSDO salesPlanSDO) {
        SalesPlan salesPlan = convertSalesPlan(salesPlanSDO);
        return salesPlanService.updateSalesPlan(salesPlan).getCount() > 0;
    }

    private SalesPlan convertSalesPlan(SalesPlanSDO source) {
        if (null == source) {
            return null;
        }
        SalesPlan target = new SalesPlan();
        target.setId(source.getId());
        target.setModel(source.getModel());
        target.setParentId(source.getParentId());
        target.setCompany(source.getCompany());
        target.setOrgBusinessUnitCode(source.getOrgBusinessUnitCode());
        target.setPlanTime(source.getPlanTime());
        target.setStartTime(source.getStartTime());
        target.setEndTime(source.getEndTime());
        target.setStatus(source.getStatus());
        target.setCheckStatus(source.getCheckStatus());
        target.setSyncInterface(source.getSyncInterface());
        target.setVersion(source.getVersion());
        target.setFeatures(source.getFeatures());
        target.setGmtCreate(source.getGmtCreate());
        target.setGmtModified(source.getGmtModified());
        target.setCreator(source.getCreator());
        target.setUpdater(source.getUpdater());
        target.setTenantId(source.getTenantId());
        return target;
    }

    @Override
    @RepositoryInvoker
    public Integer updateSalesPlanStatus(SalesPlanSDO salesPlanSDO) {
        UpdateSalesPlanStatusRequest updateSalesPlanStatusRequest = new UpdateSalesPlanStatusRequest();
        updateSalesPlanStatusRequest.setIds(Lists.newArrayList(salesPlanSDO.getId()));
        updateSalesPlanStatusRequest.setStatus(salesPlanSDO.getStatus());
        UpdateSalesPlanStatusResponse updateSalesPlanStatusResponse = salesPlanService.updateSalesPlanStatus(updateSalesPlanStatusRequest);
        return updateSalesPlanStatusResponse.getCount();
    }

    @Override
    @RepositoryInvoker(printLog = true)
    public PageResult<List<SalesPlanSDO>> pageQuery(PageQuerySalePlanRequest pageQuerySalePlanRequest) {
        LoadSalesPlanListRequest loadSalesPlanListRequest = salePlanQueryRequestConverter(pageQuerySalePlanRequest);
        try {
            Result<List<SalesPlan>> listResult = salesPlanService.loadSalesPlanList(loadSalesPlanListRequest);
            List<SalesPlanSDO> collect = listResult.getResult().stream().map(salesPlan -> {
                SalesPlanSDO salesPlanSDO = new SalesPlanSDO();
                BeanUtils.copyProperties(salesPlan, salesPlanSDO);
                return salesPlanSDO;
            }).collect(Collectors.toList());
            return PageResult.of(collect, listResult.getTotal());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    @RepositoryInvoker(printLog = true)
    public SalesPlanSDO load(QuerySalesPlanRequest querySalesPlanRequest) {
        if (null == querySalesPlanRequest || StringUtils.isBlank(querySalesPlanRequest.getId())) {
            return null;
        }
        LoadSalesPlanRequest loadSalesPlanRequest = loadSalesPlanRequestConverter(querySalesPlanRequest);
        try {
            SalesPlan salesPlan = salesPlanService.loadSalesPlan(loadSalesPlanRequest);
            if (salesPlan == null) {
                return null;
            }
            SalesPlanSDO salesPlanSDO = new SalesPlanSDO();
            BeanUtils.copyProperties(salesPlan, salesPlanSDO);
            if (StringUtils.isNotBlank(salesPlanSDO.getFeatures())) {
                SalesPlanFeatures salesPlanFeatures = (SalesPlanFeatures) JSONObject.toBean(JSONObject.fromObject(salesPlanSDO.getFeatures()),SalesPlanFeatures.class);
                salesPlanSDO.setEstimateDiscount(salesPlanFeatures.getEstimateDiscount());
                salesPlanSDO.setMonthFirstProprtion(salesPlanFeatures.getMonthFirstProprtion());
                salesPlanSDO.setMonthMiddleProprtion(salesPlanFeatures.getMonthMiddleProprtion());
                salesPlanSDO.setMonthLastProprtion(salesPlanFeatures.getMonthLastProprtion());
                salesPlanSDO.setPlanNotice(salesPlanFeatures.getPlanNotice());
                salesPlanSDO.setOrgBusinessUnitName(salesPlanFeatures.getOrgBusinessUnitName());
                salesPlanSDO.setMonthFirst(salesPlanFeatures.getMonthFirst());
                salesPlanSDO.setMonthMiddle(salesPlanFeatures.getMonthMiddle());
                salesPlanSDO.setMonthLast(salesPlanFeatures.getMonthLast());
                salesPlanSDO.setUrl(salesPlanFeatures.getUrl());
                salesPlanSDO.setSubmitSalesOrgCode(salesPlanFeatures.getSubmitSalesOrgCode());
                salesPlanSDO.setSubmitSalesOrgName(salesPlanFeatures.getSubmitSalesOrgName());
                salesPlanSDO.setOrgEnterpriseGroupCode(salesPlanFeatures.getOrgEnterpriseGroupCode());
                salesPlanSDO.setOrgRegionCode(salesPlanFeatures.getOrgRegionCode());
                salesPlanSDO.setOrgProvinceCode(salesPlanFeatures.getOrgProvinceCode());
                salesPlanSDO.setOrgProvinceId(salesPlanFeatures.getOrgProvinceId());
            }
            return salesPlanSDO;
        } catch (Exception e) {
            log.error("SalesPlanRepositoryImpl.load.exception:{}", e);
        }
        return null;
    }

    @Override
    public List<SalesPlanSDO> batchQuerySalesPlan(BatchQuerySalesPlanRequest batchQuerySalesPlanRequest) {
        com.epoch.app.bcorder.sales_plan.salesplan.dto.BatchQuerySalesPlanRequest batchQuerySalesPlanRequest1 = new com.epoch.app.bcorder.sales_plan.salesplan.dto.BatchQuerySalesPlanRequest();
        if (null != batchQuerySalesPlanRequest.getIds()) {
            batchQuerySalesPlanRequest1.setIds(batchQuerySalesPlanRequest.getIds());
        }
        BatchQuerySalesPlanResponse batchQuerySalesPlanResponse = salesPlanService.batchQuerySalesPlan(batchQuerySalesPlanRequest1);
        List<SalesPlanSDO> salesPlanSDOList = batchQuerySalesPlanResponse.getResult().stream().map(salesPlan -> {
            SalesPlanSDO salesPlanSDO = new SalesPlanSDO();
            BeanUtils.copyProperties(salesPlan, salesPlanSDO);
            if (StringUtils.isNotBlank(salesPlanSDO.getFeatures())) {
                SalesPlanFeatures salesPlanFeatures = (SalesPlanFeatures) JSONObject.toBean(JSONObject.fromObject(salesPlanSDO.getFeatures()), SalesPlanFeatures.class);
                salesPlanSDO.setEstimateDiscount(salesPlanFeatures.getEstimateDiscount());
                salesPlanSDO.setMonthFirstProprtion(salesPlanFeatures.getMonthFirstProprtion());
                salesPlanSDO.setMonthMiddleProprtion(salesPlanFeatures.getMonthMiddleProprtion());
                salesPlanSDO.setMonthLastProprtion(salesPlanFeatures.getMonthLastProprtion());
                salesPlanSDO.setPlanNotice(salesPlanFeatures.getPlanNotice());
                salesPlanSDO.setOrgBusinessUnitName(salesPlanFeatures.getOrgBusinessUnitName());
                salesPlanSDO.setMonthFirst(salesPlanFeatures.getMonthFirst());
                salesPlanSDO.setMonthMiddle(salesPlanFeatures.getMonthMiddle());
                salesPlanSDO.setMonthLast(salesPlanFeatures.getMonthLast());
                salesPlanSDO.setUrl(salesPlanFeatures.getUrl());
                salesPlanSDO.setSubmitSalesOrgCode(salesPlanFeatures.getSubmitSalesOrgCode());
                salesPlanSDO.setSubmitSalesOrgName(salesPlanFeatures.getSubmitSalesOrgName());
            }
            return salesPlanSDO;
        }).collect(Collectors.toList());
        return salesPlanSDOList;
    }

    @Override
    @RepositoryInvoker(printLog = true)
    public SalesPlanSDO loadLatelySalesPlan(QuerySalesPlanRequest querySalesPlanRequest) {
        LoadLatelySalesPlanRequest loadLatelySalesPlanRequest = LoadLatelySalesPlanRequest.builder().build();
        if (StringUtil.isNotEmpty(querySalesPlanRequest.getPlanTime())) {
            loadLatelySalesPlanRequest.setPlanTime(querySalesPlanRequest.getPlanTime());
        }
        if (StringUtil.isNotEmpty(querySalesPlanRequest.getOrgBusinessUnitCode())) {
            loadLatelySalesPlanRequest.setOrgBusinessUnitCode(querySalesPlanRequest.getOrgBusinessUnitCode());
        }
        if (null != querySalesPlanRequest.getModel()) {
            loadLatelySalesPlanRequest.setModel(querySalesPlanRequest.getModel());
        }
        //默认不传status,只查最近已发布的月度计划
        if (null != querySalesPlanRequest.getStatus()) {
            loadLatelySalesPlanRequest.setStatus(querySalesPlanRequest.getStatus());
        } else{
            loadLatelySalesPlanRequest.setStatus(SalesPlanStatusEnum.PUBLISHED.getCode());
        }
        SalesPlan salesPlan = salesPlanService.loadLatelySalesPlan(loadLatelySalesPlanRequest);
        if (Objects.isNull(salesPlan) || salesPlan.getId() == null) {
            return null;
        }
        SalesPlanSDO salesPlanSDO = new SalesPlanSDO();
        BeanUtils.copyProperties(salesPlan, salesPlanSDO);
        return salesPlanSDO;
    }

    @Override
    public List<SalesPlanSDO> loadLatelySalesPlans(QuerySalesPlanRequest querySalesPlanRequest) {
        LoadLatelySalesPlansRequest loadLatelySalesPlanRequest = LoadLatelySalesPlansRequest.builder().build();
        if (StringUtil.isNotEmpty(querySalesPlanRequest.getPlanTime())) {
            loadLatelySalesPlanRequest.setPlanTime(querySalesPlanRequest.getPlanTime());
        }
        if (StringUtil.isNotEmpty(querySalesPlanRequest.getOrgBusinessUnitCode())) {
            loadLatelySalesPlanRequest.setOrgBusinessUnitCode(querySalesPlanRequest.getOrgBusinessUnitCode());
        }
        if (null != querySalesPlanRequest.getModel()) {
            loadLatelySalesPlanRequest.setModel(querySalesPlanRequest.getModel());
        }
        if (querySalesPlanRequest.getOrgBusinessUnitCodes().size() > 0) {
            loadLatelySalesPlanRequest.setOrgBusinessUnitCodes(querySalesPlanRequest.getOrgBusinessUnitCodes());
        }
        Result<List<SalesPlan>> listResult = salesPlanService.loadLatelySalesPlans(loadLatelySalesPlanRequest);
        List<SalesPlanSDO> collect = listResult.getResult().stream().map(salesPlan -> {
            SalesPlanSDO salesPlanSDO = new SalesPlanSDO();
            BeanUtils.copyProperties(salesPlan, salesPlanSDO);
            //features
            if (StringUtil.isNotEmpty(salesPlan.getFeatures())) {
                SalesPlanFeatures salesPlanFeatures = (SalesPlanFeatures) JSONObject.toBean(JSONObject.fromObject(salesPlan.getFeatures()), SalesPlanFeatures.class);
                BeanUtils.copyProperties(salesPlanFeatures, salesPlanSDO);
            }
            return salesPlanSDO;
        }).collect(Collectors.toList());
        return collect;
    }

    @Override
    public SalesPlanFeatures convertSalesPlanFeatures(String featuresJsonString) {
        SalesPlanFeatures salesPlanFeatures = JSON.parseObject(featuresJsonString, SalesPlanFeatures.class);
        if (StringUtils.isNotBlank(salesPlanFeatures.getSubmitSalesOrgCode()) && StringUtils.isNotBlank(salesPlanFeatures.getSubmitSalesOrgName())) {
            return salesPlanFeatures;
        }
        Result<QuerySuperiorSalesOrganizationResponse> result = organizationQueryService.queryEnterpriseGroupOrg();
        if (result!=null && Objects.nonNull(result.getResult())) {
            if(StringUtils.isBlank(salesPlanFeatures.getSubmitSalesOrgCode())){
                salesPlanFeatures.setSubmitSalesOrgCode(result.getResult().getEnterpriseGroup().getCode());
            }
            if(StringUtils.isBlank(salesPlanFeatures.getSubmitSalesOrgName())){
                salesPlanFeatures.setSubmitSalesOrgName(result.getResult().getEnterpriseGroup().getName());
            }
        }
        return salesPlanFeatures;
    }

    private SalesPlan salesPlanConverter(SalesPlanSDO salesPlanSDO) {
        SalesPlan salesPlan = new SalesPlan();
        BeanUtils.copyProperties(salesPlanSDO, salesPlan);
        //features
        SalesPlanFeatures salesPlanFeatures = new SalesPlanFeatures();
        if (StringUtils.isNotBlank(salesPlanSDO.getFeatures())) {
            salesPlanFeatures = (SalesPlanFeatures) JSONObject.toBean(JSONObject.fromObject(salesPlanSDO.getFeatures()), SalesPlanFeatures.class);
        }
        salesPlanFeatures.setEstimateDiscount(Optional.ofNullable(salesPlanSDO.getEstimateDiscount()).orElse(new BigDecimal(0)));
        salesPlanFeatures.setMonthFirstProprtion(salesPlanSDO.getMonthFirstProprtion());
        salesPlanFeatures.setMonthMiddleProprtion(salesPlanSDO.getMonthMiddleProprtion());
        salesPlanFeatures.setMonthLastProprtion(salesPlanSDO.getMonthLastProprtion());
        salesPlanFeatures.setPlanNotice(salesPlanSDO.getPlanNotice());
        salesPlanFeatures.setMonthFirst(salesPlanSDO.getMonthFirst());
        salesPlanFeatures.setMonthMiddle(salesPlanSDO.getMonthMiddle());
        salesPlanFeatures.setMonthLast(salesPlanSDO.getMonthLast());
        salesPlanFeatures.setUrl(salesPlanSDO.getUrl());
        salesPlanFeatures.setSubmitSalesOrgCode(salesPlanSDO.getSubmitSalesOrgCode());
        salesPlanFeatures.setSubmitSalesOrgName(salesPlanSDO.getSubmitSalesOrgName());
        salesPlan.setFeatures(JSON.toJSONString(salesPlanFeatures));
        return salesPlan;
    }

    private LoadSalesPlanListRequest salePlanQueryRequestConverter(PageQuerySalePlanRequest pageQuerySalePlanRequest) {
        LoadSalesPlanListRequest loadSalesPlanListRequest = new LoadSalesPlanListRequest();
        BeanUtils.copyProperties(pageQuerySalePlanRequest, loadSalesPlanListRequest);
        if (StringUtil.isNotEmpty(pageQuerySalePlanRequest.getStatus())) {
            loadSalesPlanListRequest.setStatus(Integer.valueOf(pageQuerySalePlanRequest.getStatus()));
        }
        if (StringUtil.isNotEmpty(pageQuerySalePlanRequest.getPlanTime())) {
            loadSalesPlanListRequest.setPlanTime(DateUtils.dateToStamp(pageQuerySalePlanRequest.getPlanTime() + "-01 00:00:00"));
        }
        if (StringUtil.isNotEmpty(pageQuerySalePlanRequest.getPlanStartTime())) {
            loadSalesPlanListRequest.setPlanStartTime(DateUtils.dateToStamp(pageQuerySalePlanRequest.getPlanStartTime() + "-01 00:00:00"));
        }
        if (StringUtil.isNotEmpty(pageQuerySalePlanRequest.getPlanEndTime())) {
            loadSalesPlanListRequest.setPlanEndTime(DateUtils.dateToStamp(pageQuerySalePlanRequest.getPlanEndTime() + "-01 00:00:00"));
        }
        if (StringUtil.isNotEmpty(pageQuerySalePlanRequest.getId())) {
            loadSalesPlanListRequest.setId(new Long(pageQuerySalePlanRequest.getId().trim()));
        }
        if (CollectionUtils.isNotEmpty(pageQuerySalePlanRequest.getStatusList())) {
            loadSalesPlanListRequest.setStatusList(pageQuerySalePlanRequest.getStatusList());
        }
        if (StringUtil.isNotEmpty(pageQuerySalePlanRequest.getOrgBusinessUnitCode())){
            loadSalesPlanListRequest.setOrgBusinessUnitCodes(Lists.newArrayList(pageQuerySalePlanRequest.getOrgBusinessUnitCode()));
        }
        loadSalesPlanListRequest.setParentId(Optional.ofNullable(pageQuerySalePlanRequest.getParentId()).map(Integer::valueOf).orElse(null));
        return loadSalesPlanListRequest;
    }

    private LoadSalesPlanRequest loadSalesPlanRequestConverter(QuerySalesPlanRequest querySalesPlanRequest) {
        LoadSalesPlanRequest loadSalesPlanRequest = new LoadSalesPlanRequest();
        BeanUtils.copyProperties(querySalesPlanRequest, loadSalesPlanRequest);
        return loadSalesPlanRequest;
    }
}
